package com.itboye.lottery.activity.daletou

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.itboye.bylibrary.listener.MyClickListener
import com.itboye.lottery.R
import com.itboye.lottery.activity.LqBetListActivity
import com.itboye.lottery.activity.WebActivity
import com.itboye.lottery.activity.ZqBetListActivity
import com.itboye.lottery.adapter.base.BascketballExpandableListAdapter
import com.itboye.lottery.alert.ByAlert
import com.itboye.lottery.base.BaseActivity
import com.itboye.lottery.bean.BascketballBean
import com.itboye.lottery.bean.FootballMatchBean
import com.itboye.lottery.enums.LotteryType
import com.itboye.lottery.popupwindow.MyLotteryMenuPopUpWindow
import com.itboye.lottery.presenter.UserPresenter
import com.itboye.lottery.retrofit.ResponseCallback
import com.itboye.lottery.utils.BetSelectMatches
import com.itboye.lottery.utils.ConstUrl
import kotlinx.android.synthetic.main.activity_football_main.*
import org.json.JSONObject
import java.io.Serializable

class BascketballMainActivity : BaseActivity(), ResponseCallback {


    var userPresenter: UserPresenter = UserPresenter(this)
    var lay_transroot: LinearLayout? = null
    var toolbar_hiti: TextView? = null
    var toolbar_confirm: TextView? = null
    var toolbar_delete: TextView? = null


    companion object {
        var activity: BascketballMainActivity? = null
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_football_main
    }

    override fun initData() {
        activity = this
        initTitle()
        initPoupwindow()
        bindTl_Vp()
    }

    var isClickTitle = false
    private fun initTitle() {
        setTitle("竞彩篮球", MyClickListener {
            setTitleRightDrawble(when (isClickTitle) {
                true -> {
                    R.mipmap.trangle_down
                }
                false -> {
                    R.mipmap.trangle_up
                }
            })
            isClickTitle = !isClickTitle
            if (!popUpWindow!!.isShowing) {
                popUpWindow!!.setPager(pager!!)
                popUpWindow!!.setOnDismissListener {
                    isClickTitle = !isClickTitle
                    setTitleRightDrawble(R.mipmap.trangle_down)
                }
                popUpWindow!!.showMyAsDropDown(lay_transroot)
            }
        })
        rightTextValue("玩法说明", MyClickListener {
            startActivity(Intent(this, WebActivity::class.java).putExtra("title", "玩法说明").putExtra("url", ConstUrl.play_method_url + "?type=" + ConstUrl.TYPE_BASCKETBALL))
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        clearSelctCache()
    }

    private var names: Array<out String>? = null

    private var popUpWindow: MyLotteryMenuPopUpWindow? = null
    private var pager: Int = 0
    var lottery = arrayListOf(LotteryType.HUNTOU, LotteryType.SPF, LotteryType.RSPF, LotteryType.ZJQ, LotteryType.BF, LotteryType.BQC)
    var lotteryType: LotteryType = lottery[0]
    private fun initPoupwindow() {
        names = resources.getStringArray(
                R.array.jclq_types_name_list)
        val types = resources.getStringArray(R.array.jczq_types_list)
        popUpWindow = MyLotteryMenuPopUpWindow(this, names, types, 0, AdapterView.OnItemClickListener { parent, view, position, id ->
            //            closeLoadingLayout()
            pager = position
            this.lotteryType = lottery[position]
            setTitle(names!![position])
            popUpWindow!!.notifyDataSetChanged()
            if (popUpWindow!!.isShowing) {
                popUpWindow!!.dismiss()
            }
//                DataUtil.getJCZQMatchInfoDG(jczqData)//胜平负
//            } else {
//                DataUti//
//////            if (pager == 6) {l.getJCZQMatchInfo(jczqData)//胜平负
//            }
            adapter?.setPager(pager)
            clearSelctCache()
            expandAll()
//            if (zq_jczqChilds.size() <= 0)
//                showEmptyLayout("暂无比赛~", R.mipmap.img_blank_match)
        }, PopupWindow.OnDismissListener {
            //            startAnimation(ivTitleIcon, R.anim.rotate_180_360)
        })
    }

    fun clearSelctCache() {
        if (BetSelectMatches.bascketballMap!=null) {
            BetSelectMatches.bascketballMap.clear()
        }
        if (BetSelectMatches.bascketballHashSet!=null) {
            BetSelectMatches.bascketballHashSet.clear()
        }
        if (adapter != null) {
            adapter?.caculateTotalSelectMatches()
        }
    }

    fun notifyData() {
        if (adapter!=null) {
            adapter?.notifyDataSetChanged()
        }

    }

    private fun getMatchData() {
        userPresenter.getBasketballMatch()
    }

    private fun bindTl_Vp() {
        sr_refresh.autoRefresh()
        sr_refresh.setOnRefreshListener {
            getMatchData()
        }
//        orderFragments = ArrayList()
//        orderFragments!!.add(BascketballFragment())
//        orderFragments!!.add(BascketballFragment())
//        orderFragments!!.add(BascketballFragment())
//        vp_football.adapter = CommonPagerAdapter(this, orderFragments, R.array.football_title, supportFragmentManager)
//        vp_football.offscreenPageLimit = 5
//        tl_football.setupWithViewPager(vp_football)
//        vp_football.setCurrentItem(intent.getIntExtra("order_position", 0), false)
    }


    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.toolbar_confirm -> {
                if (adapter == null) {
                    ByAlert.alert("当前没有比赛数据！")
                    return
                }
                var isDg = isDG()
                if ((adapter!!.matchCount < 1 && isDg) || ((!isDg) && adapter!!.matchCount < 2)) {
                    ByAlert.alert("至少选择2场比赛！")
                    return
                }
//                if (adapter!!.matchCount < 2) {
//                    ByAlert.alert("至少选择2场比赛！")
//                    return
//                }
                if (ZqBetListActivity.activity != null) {
                    ZqBetListActivity.activity.finish()
                }
                startActivity(Intent(this, LqBetListActivity::class.java)
                        .putExtra("map", adapter!!.map as (Serializable))
                        .putExtra("pager", pager)
                        .putExtra("isDg", isDg)
                        .putExtra("lotteryType", lotteryType)
                        .putExtra("arrayList", adapter!!.zqBetListItemArrayList)
                        .putExtra("old_arrayList", data))//将初始数据传入
            }
            R.id.toolbar_delete -> {
                if (adapter == null) {
                    ByAlert.alert("当前没有比赛数据！")
                    return
                }
                adapter!!.deleteSelect()
            }
            else -> {
            }
        }
    }

    private fun isDG(): Boolean {
        var isDg = false
        var iterator = adapter!!.map.keys
        var dgCount = 0 //单关数量
        var fdgCount = 0//非单关数量
        for (s in iterator) {
            val get: Map<String, String> = adapter!!.map[s]!!
            var iterator = get.keys
            iterator.forEachIndexed { index, s ->
                if (s.split("_")[5] == "1") {
                    isDg = true
                    dgCount++
//                    return isDg
                } else {
                    fdgCount++
                    isDg = false
                }
            }
        }
        if (dgCount > 0 && fdgCount <= 0) {//全单关
            isDg = true
        } else if (dgCount > 0 && fdgCount > 0) {//既有单关又有非单关
            isDg = false
        } else if (dgCount <= 0) {//全非单关
            isDg = false
        }
        return isDg
    }

    var data: ArrayList<FootballMatchBean> = ArrayList()


    private var adapter: BascketballExpandableListAdapter? = null

    override fun success(o: Any, requestSuccessType: String) {
        sr_refresh.isRefreshing = false
        when (requestSuccessType) {
            userPresenter.getBasketballMatch_SUCCESS -> {
                //返回的O 为LinkMap格式，需要转换为json数据
                var gson = GsonBuilder().enableComplexMapKeySerialization().create()
//                var jsonString = "{\"2018-09-09\":[{\"status\":\"Selling\",\"h_order\":\"[\\u897f\\u90e81]\",\"a_order\":\"[\\u4e1c\\u90e82]\",\"l_background_color\":\"000000\",\"l_cn_abbr\":\"\\u7f8e\\u804c\\u5973\\u7bee\",\"id\":\"110748\",\"num\":\"\\u5468\\u65e5301\",\"num_type\":\"301\",\"date\":\"2018-09-10\",\"b_date\":\"2018-09-09\",\"time\":\"03:30:00\",\"begin_time\":\"1536521400\",\"h_cn_abbr\":\"\\u98ce\\u66b4\",\"a_cn_abbr\":\"\\u795e\\u79d8\\u4eba\",\n" +
//                        "\t\t\t\t\t\"WNM\":{\"special_odds\":{\"w1\":\"4.20\",\"w2\":\"3.45\",\"w3\":\"4.50\",\"w4\":\"7.80\",\"w5\":\"14.00\",\"w6\":\"15.00\",\"l1\":\"6.00\",\"l2\":\"6.90\",\"l3\":\"14.00\",\"l4\":\"30.00\",\"l5\":\"70.00\",\"l6\":\"85.00\"},\"single\":\"1\",\"add_time\":\"1536455701\",\"l\":\"\",\"odd_id\":\"8034\",\"a\":\"\",\"d\":\"\",\"h\":\"\",\"s0\":\"\",\"s1\":\"\",\"s2\":\"\",\"s3\":\"\",\"s4\":\"\",\"s5\":\"\",\"s6\":\"\",\"s7\":\"\",\"p_code\":\"WNM\",\"p_id\":\"495489\",\"fixedodds\":\"\"},\n" +
//                        "\t\t\t\t\t\t   \"HDC\":{\"special_odds\": {\"a\": \"2.60\",\"h\": \"1.31\"},\"single\": \"1\",\"add_time\": \"1536030747\", \"l\": \"\",\"odd_id\": \"7569\",\"a\": \"1.81\",\"d\": \"\",\"h\": \"1.68\",\"s0\": \"\",\"s1\": \"\",\"s2\": \"\",\"s3\": \"\",\"s4\": \"\",\"s5\": \"\",\"s6\": \"\",\"s7\": \"\",\"p_code\": \"HDC\",\"p_id\": \"495029\",\"fixedodds\": \"-4.5\"},\n" +
//                        "\t\t\t\t\t\t   \"MNL\":{\"special_odds\": {\"a\": \"2.60\",\"h\": \"1.31\"},\"single\": \"1\",\"add_time\": \"1536031021\",\"l\": \"\",\"odd_id\": \"7565\",\"a\": \"2.60\",\"d\": \"\",\"h\": \"1.31\",\"s0\": \"\",\"s1\": \"\",\"s2\": \"\",\"s3\": \"\",\"s4\": \"\",\"s5\": \"\",\"s6\": \"\",\"s7\": \"\",\"p_code\": \"MNL\",\"p_id\": \"495030\",\"fixedodds\": \"\"},\n" +
//                        "\t   \t\t\t\t\"HILO\":{\"special_odds\":\"\",\n" +
//                        "\t\t\t\t\t\t   \"single\":\"1\",\"add_time\":\"1536455701\",\"l\":\"5.55\",\"odd_id\":\"8034\",\"a\":\"\",\"d\":\"\",\"h\":\"3.33\",\"s0\":\"\",\"s1\":\"\",\"s2\":\"\",\"s3\":\"\",\"s4\":\"\",\"s5\":\"\",\"s6\":\"\",\"s7\":\"\",\"p_code\":\"WNM\",\"p_id\":\"495489\",\"fixedodds\":\"+170.5\"}\n" +
//                        "\t  }\n" +
//                        "\t]\n" +
//                        "\t}"
//                val jsonString = gson.toJson((temp))
                val jsonString = gson.toJson((o))
                data = ArrayList()
                //重新组装数据
                try {
                    var jsonObject = JSONObject(jsonString)
                    var iterator = jsonObject.keys()
                    while (iterator.hasNext()) {
                        var dataMatchInfoArray = ArrayList<BascketballBean>()
                        var footballMatchBean = FootballMatchBean()
                        var key = iterator.next()
                        val keyJSON = jsonObject.getJSONArray(key)
                        footballMatchBean.groupTime = (key)
                        for (i in 0 until keyJSON.length()) {
                            var job = keyJSON.getJSONObject(i) // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                            val type2 = object : TypeToken<BascketballBean>() {
                            }.type
                            var bean = gson.fromJson<BascketballBean>(job.toString(), type2)
                            dataMatchInfoArray.add(bean)
                        }
                        footballMatchBean.bascketballBeanArrayList = dataMatchInfoArray
                        data.add(footballMatchBean)
                        Log.v("response_data", "篮球赛事keyJSON：___________ " + data.size)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    ByAlert.alert("暂无比赛数据")
                }
                adapter = BascketballExpandableListAdapter(this, data)
                expand_lv.setAdapter(adapter)
                adapter!!.setPager(pager)
                expandAll()
                adapter!!.caculateTotalSelectMatches()
            }
            else -> {
            }
        }
    }


    fun expandAll() {
        if (adapter == null) return
        for (i in 0 until adapter!!.groupCount) {// 默认全部展开
            expand_lv.collapseGroup(i)
            expand_lv.expandGroup(i)
        }
    }


    override fun fail(code: Int, msg: Any, requestErrorType: String) {
        sr_refresh.isRefreshing = false
        ByAlert.alert(msg)
    }
}
